<?php

/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2023/10/19 14:21
 * Desc: 组合产品
 */
class Service_Api_Combination extends Contract_Api_Product
{
    public function search(array $params = array()): array
    {
        /**
         * @var $mid
         * @var $attr_id
         * @var $dest_id
         * @var $price_id
         * @var $keyword
         * @var $sort
         * @var $page
         * @var $pagesize
         * @var $status
         */
        extract($params);

        $type_id = Model_Api_V2_Combination::TYPE_ID;
        $builder = DB::select(
            'a.id', 'a.title', 'a.sellpoint', 'a.bookcount', 'a.litpic', 'a.iconlist',
            DB::expr('(IFNULL(`sline_a`.bookcount,0)+IFNULL(`sline_b`.sell_num,0)) AS sell_num')
        )
            ->from(array('combination', 'a'));

        // 需要提前处理真实购买量
        $builder->join(array('member_order_statistic', 'b'), 'left')
            ->on('b.product_id', '=', DB::expr('`sline_a`.id'))
            ->on('b.type_id', '=', $type_id);

        $builder->where(DB::expr("  FIND_IN_SET({$platform_no},sline_a.platform)"));

        // 查询推荐信息: $status = 1 时查询推荐产品， 2 为热门，过滤掉推荐产品
        if (!empty($status)) {
            // is_recommend: 0是推荐 1不是推荐
            if ($status == 1) {
                $builder->where('a.is_recommend', '!=', 1);
            } else if ($status == 2) {
                $builder->where('a.is_recommend', '=', 1);
            }
        }
        /*目的地搜索*/
        if (!empty($dest_id)) {
            $builder->where(DB::expr(" AND FIND_IN_SET({$dest_id},sline_a.kindlist) "));
        }
        /*关键词搜索*/
        if (!empty($keyword)) {
            $builder->where('a.title', 'like', "%{$keyword}%");
        }
        //价格区间
        if ($price_id) {
            $price_arr = DB::select()
                ->from('combination_pricelist')
                ->where('id', '=', $price_id)
                ->execute()
                ->current();
            if (!empty($price_arr)) {
                if (empty($price_arr['lowerprice'])) {
                    $builder->and_where('a.price', '<', $price_arr['highprice']);
                } elseif (empty($price_arr['highprice'])) {
                    $builder->and_where('a.price', '>', $price_arr['lowerprice']);
                } else {
                    $builder->and_where(DB::expr(" AND sline_a.price BETWEEN {$price_arr['lowerprice']} AND {$price_arr['highprice']}"));
                }
            }
        }
        //按属性
        if (!empty($attr_id)) {
            $attr_where = Product::get_attr_where($attr_id);
            if ($attr_where) {
                $attr_where = str_replace('a.', 'sline_a.', $attr_where);
                $builder->and_where(DB::expr($attr_where));
            }
        }

        $sort = !empty($sort) ? $sort : 0;
        switch ($sort) {
            case 1:
                $order_by = " sline_a.price ASC";
                break;
            case 2:
                $order_by = " sline_a.price DESC";
                break;
            case 3:
                $order_by = " sell_num ASC";
                break;
            case 4:
                $order_by = " sell_num DESC";
                break;
            default:
                $order_by = "  IFNULL(sline_a.display_order,9999),sline_a.modtime,sline_a.addtime ASC ";
        }

        $page     = !empty($page) ? $page : 1;
        $pagesize = !empty($pagesize) ? $pagesize : 10;
        $offset   = St_Page::offset($page, $pagesize);

        $total = $builder->execute()->count();
        $list  = $builder->offset($offset)->limit($pagesize)->order_by(DB::expr($order_by))->execute()->as_array();
        if(!empty($list)){
            // 获取营销策略
            $marketing_strategy = Model_Api_V2_Marketing_Strategy::get_instance($type_id, array('mid'=> $mid));

            foreach ($list as &$v) {
                $v['litpic'] = $this->img_url($v['litpic']);
                $v['price']  = Model_Api_V2_Combination::get_total_min_price($v['id']);
                $v['marketing_strategy'] = $marketing_strategy->get_support_application($v['id']);
            }
        }
        return array(
            'list' => $list,
            'total' => $total
        );
    }

    public function info(array $params = array()): array
    {
        $id   = $params['id'];
        $info = DB::select(
            "id", "title", "sellpoint", "bookcount", "kindlist", "finaldestid", "attrid", "iconlist", "litpic",
            "piclist", "refund", "price", "is_recommend", "auto_close_time", "satisfyscore", "several"
        )
            ->from('combination')
            ->where("id", "=", "{$id}")
            ->and_where(DB::expr(" and FIND_IN_SET({$params['platform_no']},platform)"))
            ->execute()
            ->current();
        if (empty($info)) {
            throw new Exception('产品不存在');
        }

        $info['bookcount'] = Model_Member_Order_statistic::get_sell_num(Model_Api_V2_Combination::TYPE_ID, $id);
        $info['type_name'] = Model_Api_V2_Combination::get_product_type_name($id);
        $info['piclist']   = $this->pic_list_url($info['piclist']);
        $info['litpic']    = $this->img_url($info['litpic']);
        $info['price']     = Model_Api_V2_Combination::get_total_min_price($id);
        $info['usetourer'] = Model_Sysconfig::get_sys_conf('value', 'cfg_plugin_combination_usetourer');

        $extend_info       = Model_Api_V2_Combination::get_extend_info($id);
        if (!empty($extend_info)) {
            foreach ($extend_info as &$v) {
                $v['content'] = $this->content_add_domain($v['content']);
            }
        }
        $info['extend_info'] = $extend_info;

        unset($info['attrid'], $info['kindlist'], $info['finaldestid'], $info['iconlist']);

        return $info;
    }

    public function query_condition(): array
    {
        // 自定义属性
        $attr = Model_Api_V2_Combination::get_attributes();

        // 价格属性
        $price_attr = DB::select('id', 'lowerprice', 'highprice')
            ->from('combination_pricelist')
            ->execute()
            ->as_array();
        $icon       = Currency_Tool::symbol();
        foreach ($price_attr as &$v) {
            $v['name'] = $icon . $v['lowerprice'] . '-' . $icon . $v['highprice'];
        }

        // 排序
        $sort = array(
            array('title' => '综合排序', 'id' => 0),
            array('title' => '价格从低到高', 'id' => 1),
            array('title' => '价格从高到低', 'id' => 2),
            array('title' => '销量从低到高', 'id' => 3),
            array('title' => '销量从高到低', 'id' => 4)
        );

        return array(
            'attr' => $attr['attr_list'],
            'price_attr' => $price_attr,
            'sort' => $sort,
            'index_attr' => $attr['index_attr']
        );
    }

    public function create_order(array $params = array()): array
    {
        $type_id = Model_Api_V2_Combination::TYPE_ID;
        $line              = $params['line'];
        $params['line']    = json_decode($line, true);
        $hotel             = $params['hotel'];
        $params['hotel']   = json_decode($hotel, true);
        $car               = $params['car'];
        $params['car']     = json_decode($car, true);
        $spot              = $params['spot'];
        $params['spot']    = json_decode($spot, true);
        $outdoor           = $params['outdoor'];
        $params['outdoor'] = json_decode($outdoor, true);
        $tourist           = $params['tourist'];
        $params['tourist'] = json_decode($tourist, true);

        //产品信息
        $combination_info = DB::select()
            ->from('combination')
            ->where('id', '=', $params['combination_id'])
            ->and_where('ishidden', '=', 0)
            ->execute()
            ->current();
        if (!$combination_info) {
            throw new Exception('产品不存在');
        }

        $mid         = $params['mid'];
        $member_info = $params['member_info'];

        /*积分抵现*/
        $needJifen   = intval($params['needjifen']);
        $jifentprice = 0;
        $useJifen    = 0;
        if ($needJifen) {
            $jifentprice = Model_Jifen_Price::calculate_jifentprice($combination_info['jifentprice_id'], $type_id, $needJifen, $member_info);
            $useJifen    = empty($jifentprice) ? 0 : 1;
            $needJifen   = empty($jifentprice) ? 0 : $needJifen;
        }

        /*积分评论*/
        $jifencomment_info = Model_Jifen::get_used_jifencomment($type_id);
        $jifencomment      = empty($jifencomment_info) ? 0 : $jifencomment_info['value'];

        $totalprice = Model_Combination::get_total_price($params);
        $ordersn = Product::get_ordersn($type_id);
        $order   = array(
            'ordersn' => $ordersn,
            'webid' => 0,
            'typeid' => $type_id,
            'productautoid' => $params['combination_id'],
            'productname' => $combination_info['title'],
            'litpic' => $combination_info['litpic'],
            'price' => $totalprice,
            'childprice' => 0,
            'paytype' => 1,
            'dingjin' => '',
            'usedate' => '',
            'departdate' => '',
            'addtime' => time(),
            'memberid' => $params['mid'],
            'dingnum' => $params['several'],
            'childnum' => 0,
            'oldprice' => 0,
            'oldnum' => 0,
            'linkman' => $params['link_name'],
            'linktel' => $params['link_tel'],
            'linkemail' => $params['link_email'],
            'haschild' => 1,
            'suitid' => 0,
            'remark' => $params['remark'],
            'status' => 1,
            'source' => $params['source'],//来源,
            'auto_close_time' => $combination_info['auto_close_time'] + time(), //自动关闭订单时间,
            'refund_restriction' => $combination_info['refund'],
            'usejifen' => $useJifen,
            'needjifen' => $needJifen,
            'jifentprice' => $jifentprice,
            'jifenbook' => $combination_info['jifenbook_id'],
            'jifencomment' => $jifencomment,
        );

        // 处理优惠券
        $coupon_id = Arr::get($params, 'coupon_id', '');
        if ($coupon_id) {
            $coupon_check = Model_Api_V2_Coupon::order_use_coupon_check($coupon_id, $mid, $order);
        }

        // 优惠券
        if (!empty($coupon_check)) {
            Model_Coupon::add_coupon_order($coupon_check['cid'], $order['ordersn'], $coupon_check['order_total_price'], $coupon_check, $coupon_id);
        }

        // 添加主订单
        $res = Model_Api_V2_Order::add_order($order, 'Model_Combination');
        if (!$res['status']) {
            throw new Exception($res['msg']);
        }

        // 获取主订单信息
        $order_info = DB::select('id', 'ordersn', 'typeid')
            ->from('member_order')
            ->where('ordersn', '=', $ordersn)
            ->execute()
            ->current();

        // 添加子订单
        $add_sub_order_res = Model_Combination::add_sub_order($params, $ordersn);
        if (!$add_sub_order_res['status']) {
            /*子订单里存在有下单失败的订单时，删除成功的部分*/
            Model_Combination::delete_order($order_info['id']);
            throw new Exception($add_sub_order_res['msg']);
        }

        //添加红包抵扣
        if (St_Functions::is_normal_app_install('red_envelope') && $params['envelope_member_id']) {
            Model_Order_Envelope::order_use_envelope($params['envelope_member_id'], $order['ordersn'], $type_id, $mid);
        }

        /*子订单创建成功后，更新主订单信息*/
        Model_Member_Order_Compute::update($order_info['ordersn']);

        // 事件
        Hook::trigger('order_created', $order);

        // 返回订单信息
        $order_info['orderid'] = $order_info['id'];
        $filter_keys           = array('id', 'orderid', 'ordersn', 'pageType', 'typeid', 'status');
        return $this->filter_data($filter_keys, $order_info);
    }

    use Trait_Api_Combination;
}